package com.example.demo.project.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.common.annotation.NotNUll;
import com.example.demo.project.entity.Student;
import com.example.demo.project.mapper.StudentMapper;
import com.example.demo.project.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/student")
public class StudentController {
    @Resource
    private StudentMapper studentMapper;
    @Autowired
    private StudentService studentService;
    //新增和修改
    @PostMapping("/save")
    public Result save(@RequestBody Student student){
        return Result.success(studentService.saveStudent(student));
    }
    @GetMapping("/list")
    public Result findAll(@NotNUll(message = "不能为空") int num){
        Page<Student> page = new Page<>(1,8);
        return Result.success(studentMapper.queryAllStudent(page));
        //需要做redis缓存处理
//        Object o = RedisUtil.get(XlQuestionRedisConstant.GET_STUDENT_QUESTION_BANK + xlExamMultiList.get(i).getQuestionBankId());
//        if (o != null) {
//            xlExamStudentMulti=(XlExamStudentMulti) o;
//        } else {
//            xlExamStudentMulti = xlQuestionBankService.getStudentQuestionBank(xlExamMultiList.get(i).getQuestionBankId());
//            RedisUtil.set(XlQuestionRedisConstant.GET_STUDENT_QUESTION_BANK + xlExamMultiList.get(i).getQuestionBankId(),xlExamStudentMulti);
//        }
    }
    @GetMapping("/delete")
    public Result delete(@RequestParam String[] id){
//        Wrapper<Student> wrapper =new Wrapper<>();
        Collection ids = Arrays.asList(id);
        return Result.success(studentService.removeByIds(ids));
    }
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "1") Long pageNum,
                                   @RequestParam(defaultValue = "4") Long pageSize,
                                   @RequestParam(defaultValue = "") String studentName,
                                   @RequestParam(defaultValue = "") String studentId,
                                   @RequestParam(defaultValue = "") String className
                                   ){
        IPage<Student> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if(!"".equals(studentName)){
            queryWrapper.like("student_name",studentName);
        }
        if(!"".equals(studentId)){
            queryWrapper.like("student_id",studentId);
        }
        if(!"".equals(className)){
            queryWrapper.like("class_name",className);
        }
//        queryWrapper.or().like("age",age);
        return Result.success(studentService.page(page,queryWrapper));
    }
    /**
     * Excel导出
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public Result export(HttpServletResponse response) throws IOException {
        List<Student> list = studentService.list();
        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("studentName","学生姓名");
        writer.addHeaderAlias("sex","性别");
        writer.addHeaderAlias("studentId","学号");
        writer.addHeaderAlias("className","班级");
        writer.addHeaderAlias("dorm","宿舍");
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("学生信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
        return Result.success();
    }

    /**
     * Excel导入
     * 导入的模板可以使用 Excel导出的文件
     *
     * @param file Excel
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<List<Object>> lists = ExcelUtil.getReader(inputStream).read(1);
        List<Student> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            Student user = new Student();
            user.setStudentName(row.get(0).toString());
            user.setSex(row.get(1).toString());
            user.setStudentId(row.get(2).toString());
            user.setClassName(row.get(3).toString());
            user.setDorm(row.get(4).toString());
            saveList.add(user);
        }
        for (Student user : saveList) {
            studentMapper.insert(user);
        }
        return Result.success();
    }
}
